<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <meta charset="utf-8">
    <title>Layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/toastr/toastr.css" media="all">
    <style>
        th .layui-table-cell{
            text-align: center;
            line-height: 30px;
            height: 30px;
        }
        .layui-table-cell{
            text-align: center;
            line-height: 80px;
            height: 80px;
        }
        .layui-table img{
            width: 60px;
            height: 115px;
        }
    </style>
</head>
<body>

<form action="" lay-filter="xiugai" id="updBook" class="layui-form"  hidden>
    <input type="hidden" name="bookid" lay-verify="bid"  placeholder="请输入bookid" autocomplete="off" class="layui-input">
    <div class="layui-form-item">
        <label class="layui-form-label">书名</label>
        <div class="layui-input-inline">
            <input type="text" name="bookname" lay-verify="required"   placeholder="请输入书名" autocomplete="off" class="layui-input">
        </div>
        <label class="layui-form-label">类型</label>
        <div class="layui-input-inline">
            <select name="typeid" lay-verify="required" id="addTypeId" lay-filter="aihao">
                <option value="">请选择书籍的类型</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">介绍</label>
        <div class="layui-input-inline">
            <input type="text" name="remark" lay-verify="required" placeholder="请输入该书的介绍" autocomplete="off" class="layui-input">
        </div>
        <label class="layui-form-label">价格</label>
        <div class="layui-input-inline">
            <input type="text" name="price" lay-verify="bookPrice" placeholder="请输入价格" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">作者</label>
        <div class="layui-input-inline">
            <input type="text" name="author" lay-verify="required" placeholder="请输入作者名" autocomplete="off" class="layui-input">
        </div>
        <label class="layui-form-label">出版社</label>
        <div class="layui-input-inline">
            <input type="text" lay-verify="required" name="publisher" placeholder="请输入出版社" autocomplete="off" class="layui-input">
        </div>
    </div>
    <%--<input type="hidden" name="url" id="imageUrl"   autocomplete="off" class="layui-input">--%>
    <div class="layui-upload">
        <button type="button" class="layui-btn" id="test2">多图片上传</button>
        <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
            预览图：
            <div class="layui-upload-list" id="demo2"></div>
            <input type="hidden" name="url" id="imageUrl">
        </blockquote>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="addAndUpdate">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>


<%--搜索框表单--%>
<br>
<form action=""  id="updBook" class="layui-form" >
    <div class="layui-form-item">
        <label class="layui-form-label">书名</label>
        <div class="layui-input-inline">
            <input type="text" name="bookname"  placeholder="请输入书名" autocomplete="off" class="layui-input">
        </div>
        <label class="layui-form-label">类型</label>
        <div class="layui-input-inline">
            <select name="typeid"  id="addlx" lay-filter="aihao">
                <option value="">请选择书籍的类型</option>
            </select>
        </div>
        <label class="layui-form-label">作者</label>
        <div class="layui-input-inline">
            <input type="text" name="author"  placeholder="请输入作者名" autocomplete="off" class="layui-input">
        </div>
        <div class="layui-input-inline">
            <button type="button" class="layui-btn" lay-submit lay-filter="ssss">搜索</button>
        </div>
    </div>
</form>

<%--图片详情的弹框--%>
<div id="imgDiv" style="display: none">
    <%--<h1>这是图片</h1>--%>
</div>
<%--图片重新上传的弹框--%>
<div id="chongXin" style="display: none">
    <div class="layui-upload">
        <button type="button" class="layui-btn" id="test3">多图片上传</button>
        <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
            预览图：
            <div class="layui-upload-list" id="demo3"></div>
            <input type="hidden" name="url" id="imageUrl3">
        </blockquote>
    </div>
    <button id="chongXinTiJiao" class="layui-btn layui-btn-sm">提交</button>
</div>
<%--查询页面--%>
<table class="layui-hide" id="test" lay-filter="test"></table>

<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="add"><i class="layui-icon">&#xe654;</i></button>
        <button class="layui-btn layui-btn-sm" lay-event="shuaxin"><i class="layui-icon">&#xe669;</i></button>
    </div>
</script>

<script type="text/html" id="barDemo">
    <%--当status的值是1时，此时显示表示上架，所以要显示下架--%>
    {{#  if(d.status == 1){ }}
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="shangjia">下架</a>
    <a class="layui-btn layui-btn-xs" lay-event="lookImg">图片详情</a>
    {{#  } }}
    {{#  if(d.status == 0){ }}
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-xs" lay-event="shangjia">上架</a>
    <a class="layui-btn layui-btn-xs" lay-event="lookImg">图片详情</a>
    {{#  } }}
</script>

<script src="${pageContext.request.contextPath}/layui/layui.all.js" charset="utf-8"></script>
<script src="${pageContext.request.contextPath}/toastr/toastr.js" charset="utf-8"></script>

<script>
    layui.use(['table','layer','form','jquery','upload'], function(){
        var table = layui.table;
        var layer = layui.layer;
        var $ = layui.jquery;
        var form  = layui.form;
        var upload = layui.upload;

        var s ="";
        function showupload(){
            //多图片上传
            upload.render({
                elem: '#test2'
                ,url: '${pageContext.request.contextPath}/book/upload' //改成您自己的上传接口
                ,multiple: true
                ,before: function(obj){
                    //预读本地文件示例，不支持ie8
                    obj.preview(function(index, file, result){
                        $('#demo2').append('<img height="100px" width="100px"  src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img">')
                    });
                }
                ,done: function(res){
                    s +=res.url+",";
                    //上传完毕
                    //alert(s);
                    //$("#imgpath").val(res);
                    $("#imageUrl").val(s);//将上传成功后得到的图片的url返回，并且赋值给表单中隐藏url框
                    //alert(res.str);
                    layer.msg('上传成功');
                    //layui.$('#uploadDemoView').removeClass('layui-hide').find('img').attr('src', res.str);
                }
            });
        }

        var s1 = "";
        /*重新上传的图片的上传*/
        function showuploadChongxin(){
            upload.render({
                elem: '#test3'
                ,url: '${pageContext.request.contextPath}/book/uploadReload' //改成您自己的上传接口
                ,multiple: true
                ,before: function(obj){
                    //预读本地文件示例，不支持ie8
                    obj.preview(function(index, file, result){
                        $('#demo3').append('<img height="100px" width="100px" src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img">')
                    });
                }
                ,done: function(res){
                    s1 +=res.url+"";
                    //上传完毕
                    //alert(s1);
                    //$("#imgpath").val(res);
                    $("#imageUrl3").val(s1);//将上传成功后得到的图片的url返回，并且赋值给表单中隐藏url框
                    //alert(res.str);
                    layer.msg('上传成功');
                    //layui.$('#uploadDemoView').removeClass('layui-hide').find('img').attr('src', res.str);
                }
            });
        }

        function showtable(){
            table.render({
                elem: '#test'
                ,url:'${pageContext.request.contextPath}/book/selectBook'
                ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
                ,title: '用户数据表'
                ,cols: [[
                    /*{type: 'checkbox', fixed: 'left'}
                    ,*/{field:'bookid', title:'bookid',fixed: 'left',hide:true,unresize: true, sort: true}
                    ,{field:'bookname', title:'书名'}
                    ,{field:'author', title:'作者'}
                    ,{field:'count', title:'数量'}
                    ,{field:'remark', title:'介绍',  sort: true}
                    ,{field:'typeid', title:'类型编号',hide:true}
                    ,{field:'typename', title:'类型',sort: true}
                    ,{field:'publisher', title:'出版社'}
                    ,{field:'price', title:'价格', sort: true}
                    ,{field:'status', title:'状态',templet:function (d) {
                            if (d.status == 1){
                                return '<button  class="layui-btn layui-btn-xs layui-btn-radius"   >上架</button>';
                            }else {
                                return '<button  class="layui-btn layui-btn-xs layui-btn-radius layui-btn-danger"  >下架</button>';
                            }
                        }
                    }
                    ,{field:'url', title:'图片',sort: true,templet:function (d) {
                            return '<img src="'+d.url+'" width="100px" height="50px"/>';
                        }}
                    ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:200}
                ]]
                ,even:true
                ,page: true
                ,limit:5
                ,limits:[3,5,7,9]
            });
        }

        //查询所有书籍类型，并填充到下拉框中
        function showselect(){
            $.ajax({
                type:'post',
                url:'${pageContext.request.contextPath}/type/selectType',
                dataType:'json',//预期的后台数据类型
                success:function (data) {
                    //通过循环遍历查到的所有类型，并填充到类型下拉框中
                    var op="";
                    for (var i=0;i<data.length;i++){
                        op +="<option value='"+data[i].typeid+"'>"+data[i].typename+"</option>";
                    }
                    $("#addTypeId").append(op);
                    $("#addlx").append(op);
                    form.render('select');//表单的更新渲染 下拉框
                }
            })
        }

        //页面整个加载完成时执行
        $(function () {
            showtable();
            showupload();
            showuploadChongxin();
            showselect();
        })

        //头工具栏事件
        table.on('toolbar(test)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'getCheckData':
                    var data = checkStatus.data;
                    layer.alert(JSON.stringify(data));
                    break;
                case 'add':
                    $("#updBook")[0].reset(); //新增之前 先把弹出的form表单中的值清空
                    $("#demo2").html("");
                    layer.open({
                        type: 1,
                        title:'新增信息',
                        area: ['700px', '300px'],
                        anim:6,
                        content: $('#updBook') //这里content是一个普通的String
                    });
                    break;
                case 'shuaxin':
                    showtable();
                    break;
                //自定义头工具栏右侧图标 - 提示
                case 'LAYTABLE_TIPS':
                    layer.alert('这是工具栏右侧自定义的一个图标按钮');
                    break;
            };
        });

        /*
        * 搜索表单的提交
        * */
        form.on('submit(ssss)', function(data){
            table.reload('test',{
                where:{
                    bookname:data.field.bookname,
                    typeid:data.field.typeid,
                    author:data.field.author
                },page: {
                    curr:1
                }
            })
        });

        /*
        * 增加 / 修改 表单 的验证
        * */
        form.verify({
            //我们既支持上述函数式的方式，也支持下述数组的形式
            //数组的两个值分别代表：[正则匹配、匹配不符时的提示文字]
            bookPrice: [
                /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/
                ,'只能输入正数'
            ]
        });

        // 修改和添加 按钮的表单提交事件
        form.on('submit(addAndUpdate)', function(data){
            $.ajax({
                type:'post',
                url:'${pageContext.request.contextPath}/book/updateAndInsertBook',
                dataType:'json',//预期的后台数据类型
                data:data.field,//当前表单的所有数据
                success:function (data) {
                    if (data.code == "1001"){
                        layer.closeAll();
                        layer.alert(data.msg, {icon: 1});
                    }else if (data.code == "1002"){
                        layer.closeAll();
                        layer.alert(data.msg, {icon: 5});
                    }else {
                        layer.alert(data.msg, {icon: 5});
                    }
                    showtable();
                    s="";
                }
            })
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });

        //监听行工具事件
        table.on('tool(test)', function(obj){
            var data = obj.data;
            if(obj.event === 'shangjia'){
                layer.confirm('确定要上架/下架吗', function(index){
                    $.ajax({
                        type:'post',
                        url:'${pageContext.request.contextPath}/book/updateStat',
                        dataType:'json',//预期的后台数据类型
                        data:{"bookid":data.bookid,"status":data.status},//当前表单的所有数据
                        success:function (data) {
                            if (data.code == "1001"){
                                layer.alert(data.msg, {icon: 1});
                            }else if (data.code == "1002"){
                                layer.alert(data.msg, {icon: 5});
                            }else {
                                layer.alert(data.msg, {icon: 5});
                            }
                            showtable();
                        }
                    })
                });
            } else if(obj.event === 'edit'){
                $("#updBook")[0].reset();//将弹出的表单中的内容 提前清空，然后再填值
                $("#demo2").html("");
                layer.open({
                    type: 1,
                    title:'修改信息',
                    area: ['700px', '300px'],
                    anim:6,
                    content: $('#updBook') //这里content是一个普通的String
                });
                form.val('xiugai',data);//将当前点击行的数据填充到form表单中
            }else if(obj.event === 'lookImg'){
                $("#imgDiv").html(""); //清空弹框
                var allimg = null;
                layer.open({
                    type: 1,
                    title:'图片详情',
                    area: ['700px', '300px'],
                    anim:6,
                    content: $('#imgDiv') //这里content是一个普通的String
                });
                //显示所有的该书籍的图片信息
                $.ajax({
                    type:'post',
                    url:'${pageContext.request.contextPath}/book/getImgByBookId',
                    dataType:'json',//预期的后台数据类型
                    //async:false,
                    data:{"bookid":data.bookid},//当前表单的所有数据
                    success:function (bookImg) {
                        /*allimg = bookImg;*/
                        for (var i = 0;i<bookImg.length;i++){
                            $('#imgDiv').append('<img width="100px" height="100px" src="'+ bookImg[i].url +'" class="layui-upload-img" >').append('<button class="layui-btn layui-btn-sm" value="'+bookImg[i].url+'">重新上传</button>').append('<button value="'+bookImg[i].url+'" class="layui-btn layui-btn-sm">删除</button>');
                        }

                        $("#imgDiv button").click(function () { //点击不同按钮的弹框
                            if ($(this).html() == "重新上传"){ //重新上传按钮的操作
                                var urlOld = $(this).val();
                                //重新上传的图片的调用
                                $("#demo3").html("");
                                layer.open({
                                    type: 1,
                                    title:'图片详情',
                                    area: ['700px', '300px'],
                                    anim:6,
                                    content: $('#chongXin') //这里content是一个普通的String
                                });

                                $("#chongXinTiJiao").click(function () {
                                    $.ajax({
                                        type:'post',
                                        url:'${pageContext.request.contextPath}/book/updateBookUrl',
                                        dataType:'json',//预期的后台数据类型
                                        data:{"urlOld":urlOld,"urlNew":$("#imageUrl3").val()},//当前表单的所有数据
                                        success:function (data) {
                                            layer.closeAll();
                                            if (data.code == "1001"){
                                                layer.alert(data.msg, {icon: 1});
                                            }/*else {
                                                layer.alert(data.msg, {icon: 5});
                                            }*/
                                            showtable();
                                            s1="";
                                        }
                                    })
                                })

                            }else { //删除操作
                                $.ajax({
                                    type:'post',
                                    url:'${pageContext.request.contextPath}/book/deleteBookUrl',
                                    dataType:'json',//预期的后台数据类型
                                    data:{"url":$(this).val()},//当前表单的所有数据
                                    success:function (data) {
                                        layer.closeAll();
                                        if (data.code == "1001"){
                                            layer.alert(data.msg, {icon: 1});
                                        }else {
                                            layer.alert(data.msg, {icon: 5});
                                        }
                                        showtable();
                                    }
                                })
                            }
                        })
                    }
                })
            }
        });
    });
</script>

</body>
</html>
